package pro.reznick.geoalarm;

import android.content.*;
import android.os.IBinder;

/**
 * @author alex
 * @since 8/20/11 4:34 PM
 */

public class ControllerBinderTrait
{

    public interface OnControllerBoundHandler
    {
        void onControllerBound();
    }

    public GeoAlarmController controller;
    public boolean isBound;
    public OnControllerBoundHandler controllerEventsHandler;
    public ContextWrapper implementer;

    public ControllerBinderTrait(ContextWrapper wrapper)
    {
        implementer = wrapper;
    }

    private ServiceConnection controllerConnection = new ServiceConnection()
    {
        public void onServiceConnected(ComponentName className, IBinder service)
        {
            controller = ((GeoAlarmController.ControllerBinder) service).getService();
            if (!isBound)
            {
                isBound = true;
                if (controllerEventsHandler != null)
                    controllerEventsHandler.onControllerBound();
            }
        }

        public void onServiceDisconnected(ComponentName className)
        {
            controller = null;
            isBound = false;
        }
    };


    protected void bindController()
    {
        if (!isBound)
        {
            Intent intent = new Intent(implementer, GeoAlarmController.class);
            implementer.bindService(intent, controllerConnection, Context.BIND_AUTO_CREATE);
        }
    }

    protected void unbindController()
    {
        if (isBound)
        {
            implementer.unbindService(controllerConnection);
            isBound = false;
        }
    }

}
